package com.jydd.singlekotlinmvvm.comm.feature.search

import com.jydd.singlekotlinmvvm.comm.base.BaseLiveData
import com.jydd.singlekotlinmvvm.comm.base.BaseViewModel
import com.jydd.singlekotlinmvvm.comm.client.apis.GitApi
import com.jydd.singlekotlinmvvm.comm.model.response.RepoInfo

/**
 * created by 韦敏敏
 * on 2020/1/21
 */
class SearchViewModel(private val gitApi : GitApi) : BaseViewModel() {
    private var currPage: Int = 1
    var hasMore: Boolean = true
    private val tempResult = mutableListOf<RepoInfo>()
    private val _repoResult = BaseLiveData<MutableList<RepoInfo>>()
    val repoResult: BaseLiveData<MutableList<RepoInfo>>
    get() = _repoResult
    fun fetchSearch(key : String){
        currPage = 1
        tempResult.clear()
        loadMore(key)
    }
    fun loadMore(key : String) {
        request {
            var result = gitApi.searchReps(key = key, currPage = currPage)
            tempResult.addAll(result.items)
            hasMore = tempResult.size < result.total
            if (hasMore) currPage++
            _repoResult.update(tempResult)
        }
    }

    override fun onCleared() {
        super.onCleared()
        tempResult.clear()
    }
}